import random
import logging
from django import http
from django.shortcuts import render
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.verification import contents
from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
from meiduo_mall import settings
from utils.response_code import RETCODE

logger = logging.getLogger('django')


class ImageCodeView(View):
    def get(self, request, uuid):
        name, text, image = captcha.generate_captcha()

        conn = get_redis_connection('code')
        conn.setex('img_%s' % uuid, 60, text)

        return http.HttpResponse(image, content_type='image/jpeg')


class SMSCodeView(View):
    def get(self, request, mobile):
        # 接受参数
        image_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        # 验证参数
        if not all([image_client, uuid]):
            return http.HttpResponseBadRequest('缺少参数')
        # 链接redis服务器
        conn = get_redis_connection('code')
        image_server = conn.get('img_%s' % uuid)
        image_server = image_server.decode()
        if image_server is None:
            return http.HttpResponseBadRequest('参数错误')

        try:
            conn.delete('img_%s' % uuid)
        except Exception:
            return http.HttpResponseBadRequest('参数错误')

        if image_client.lower() != image_server.lower():
            return http.JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '验证码错误'})

        sms_code = '%6d' % random.randint(100000, 999999)
        logger.info(sms_code)

        conn.setex('sms_%s' % mobile, 60, sms_code)

        CCP().send_template_sms(mobile, [sms_code, contents.SMS_CODE_REDIS_EXPIRES // 60],
                                contents.SEND_SMS_TEMPLATE_ID)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})


class SMSView(View):
    def get(self, request):
        # 接受参数
        access_token = request.GET.get('access_token')
        serializer = Serializer(settings.SECRET_KEY)
        # 教研参数
        try:
            data = serializer.loads(access_token)
        except Exception:
            return http.HttpResponseBadRequest('发生错误')
        # 生成验证码
        mobile = data.get('mobile')
        sms_code = '%6d' % random.randint(100000, 999999)
        logger.info(sms_code)

        conn = get_redis_connection('code')
        sms_server = conn.get('sms_flag_%s' % mobile)

        if sms_server:
            return http.HttpResponseBadRequest('发送过于频繁')

        try:
            conn.setex('sms_%s' % mobile, 60, sms_code)

            CCP().send_template_sms(mobile, [sms_code, contents.SMS_CODE_REDIS_EXPIRES // 60],
                                    contents.SEND_SMS_TEMPLATE_ID)
        except Exception:
            return http.HttpResponseBadRequest('发送失败')
        else:
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
